layui.use(['element', 'layer'], function(){
    var element = layui.element;
    var layer = layui.layer;
    //监听折叠
    element.on('collapse(test)', function(data){
        layer.msg('展开状态：'+ data.show);
    });
});

function fake_post(url, data, callback){
    // This structure is not specific to DataTable and is just the structure my server is returning.
    var response = {
        'type': 'table',
        'header': ['id', 'name'],
        'columns': [{'title': 'ID'}, {'title': 'Name'}],
        'data': [
            ['1', 'Homer Simpson'],
            ['2', 'Bart Simpson'],
            ['3', 'Lisa Simpson'],
            ['4', 'Ned Flanders'],
            ['5', 'Planet Earth']
        ]
    }
    callback(response);
}
function toggleSQL(){
    $("#sql-form").toggle();
    var dom = document.getElementById("toggleSQL");
    $(dom).children("i").css("fa fa-angle-double-down");
    if($(dom).children("i").hasClass("fa-angle-double-down")){

        $(dom).children("i").removeClass("fa-angle-double-down").addClass("fa fa-angle-double-up");
    }else {
        $(dom).children("i").removeClass("fa-angle-double-up").addClass("fa fa-angle-double-down");
    }
}

function save_sql(){
    var activetab = $("#subJobTabtitle .layui-this");
    var paragraphsid = activetab.attr("id");
    var notebookid = activetab.attr("notebookid");
    var text = window.editor.getValue();

    if(typeof(paragraphsid) == "undefined")
    {
        alert("请选择相应的子任务");
    }else //运行对应的接口并返回
    {
        $.ajax({
            type: "POST",
            url: "/sql/saveSql",
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify({
                "paragraphsid":paragraphsid,
                "notebookid":notebookid,
                "text":text
            }),
            success: function (data) {
                if(data.data.returnuStatus == "error")
                {
                    alert(data.data.returnMessage);
                }else
                {
                    alert("保存成功");
                }
            }
        });

    }
}

function run_tab(){
    var activetab = $("#subJobTabtitle .layui-this");
    var paragraphsid = activetab.attr("id");
    var notebookid = activetab.attr("notebookid");
    if(typeof(paragraphsid) == "undefined")
    {
        alert("请选择相应的子任务");
    }else //运行对应的接口并返回
    {
        $.ajax({
            type: "POST",
            url: "/sql/runSql",
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify({
                "paragraphsid":paragraphsid,
                "notebookid":notebookid,
                "type":"id"
            }),
            success: function (data) {
                if(data.data.returntype == 'text')
                {
                    $("#data-container").html(data.data.data);
                    $("#run-tab-result").trigger("click");
                }else if (data.data.returntype == 'table')
                {
                    //先写表
                    $("#data-container").html('<table id="demo" lay-filter="userFilter" ></table>');
                    layui.use('table', function(){
                        var table = layui.table;
                        table.init('userFilter',{//转换成静态表格
                            cols:[data.data.columndata]
                            ,data:data.data.data
                            ,limit:10
                        });
                        fake_post("editor/run-sql", {'data': sql}, function(result){
                            toggleSQL();
                        });
                    });
                    $("#run-tab-result").trigger("click");
                }else if (data.data.returntype == 'error')
                {
                    $("#data-container").html("错误信息为:"+data.data.data);
                    $("#run-tab-result").trigger("click");
                }
            }
        });

    }
}

function run_sql(){
    $('#data-container').show();
    $('#data-error').removeClass("layui-show");
    var sql = window.editor.getValue();
    layui.use('table', function(){
        var table = layui.table;
        table.render({
            elem: '#demo'
            ,url: '/sql/runSql'
            ,where:{sql:sql,type:'sql'}
            ,method:'post'
            ,contentType: 'application/json'
            ,page: true //开启分页
            ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            ,height: 500
            ,cols: [[
                { type:'numbers',align:'center', width:60,title:'序号'}
                ,{field:'access',  title: '字段名称',align:'center',width:'18%'}
            ]],
            done:function (res,page,count) {
                var myData=new Array();
                myData = res.data.columndata;
                table.init('userFilter',{//转换成静态表格
                    cols:[myData]
                    ,data:res.data.data
                    ,limit:10
                });
                fake_post("editor/run-sql", {'data': sql}, function(result){
                    toggleSQL();
                });
            }
        });
    });
}

var AUTOCOMPLETE_TABLES = {
    'hello': ['world', 'neighbor', 'there'],
    'reply': ['rumble', 'hellodley', 'hi_there']
}

window.onload = function() {
    window.editor = CodeMirror.fromTextArea(document.getElementById('code'), {
        mode: 'text/x-mysql',
        indentWithTabs: true,
        smartIndent: true,
        lineNumbers: true,
        matchBrackets : true,
        autofocus: true,
        extraKeys: {"Ctrl-Space": "autocomplete"}
    });
    window.editor.setSize('auto','auto');
    CodeMirror.commands.autocomplete = function(cm) {
        CodeMirror.showHint(cm, CodeMirror.hint.sql, {
            tables: AUTOCOMPLETE_TABLES
        });
    }
};
